<template>
  <div>
    <TopFilter ref="topfilter" :list="topFilterList" :cols="4" labelWidth="100" :collapse="true" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      :isExportExcel="false"
      exportFileName="三包法规查询.xlsx"
      :onCalcExportData="handleExportFun"
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      datakey="records"
      :isSelectColumn="false"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="add()">新增</multiuse-button>
        <multiuse-button size="small" type="primary" :click="downloadTemplate.bind()">模板下载</multiuse-button>
        <multiuse-button size="small" icon="el-icon-upload" @click="showImportFun()" >导入</multiuse-button>
      </template>
    </FilterTable>

    <Drawer :visible.sync="visibleDetail" :title="'总成及主要备件关系编辑'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <detail :partId="partId" @save="editSave" @close="closeHandler" :handleType="handleType" />
    </Drawer>
    <Drawer :visible.sync="visibleAdd" :title="'总成及主要备件关系新增'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <addForm :partId="partId" @save="addSave" @close="closeHandler" :handleType="handleType" />
    </Drawer>
    <Drawer :visible.sync="showImport" :closable="false" icon="el-icon-upload" title="导入" width="800px" destroyOnClose :containerStyle="{ height: 'calc(100% - 120px)', overflow: 'auto', paddingBottom: '60px' }">
      <importExcel @close="showImport = false" @importclose="importClose()" hideErrorMsg='true' url="/api/dmscloud.activity/ttRpThreeInfo/assemblyPart/import"/>
    </Drawer>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
import detail from './detail';
import addForm from './addForm';
import { dealerMixin } from '@/pages/repair/batchEventManagement/dealerMixin';
import importExcel from '@/pages/claimDemage/tools/importExcel.vue';
import { isEmpty } from '@/utils/utils';
import {
  downloadModel,
  assemblyPartList,
  deleteAssembly,
  deleteAssemblyPart,
  listRecord,
  exportListRecord,
  listRecordNew,
  assemblyAndRegulationslistRecordNew, assemblyAndRegulationsListRecordNew, addAssembly
} from '@/api/repair/threePacksOfManager/regulationsQueryCDuan';
import {arrayObjDeWeight, exportExcelFile} from '@/utils';

export default {
  name: 'addItem',
  mixins: [dictionary, dealerMixin],
  data() {
    this.BaseTable = null;
    this.conf = { add: '新增', edit: '编辑', show: '三包预警规则编辑' };
    return {
      topFilterList: this.createTopFilterList(),
      visible: false,
      visibleAdd: false,
      visibleDetail: false,
      showImport: false,
      fetchApi: assemblyPartList,
      dialogTitle: '',
      fetchParams: { xhrAbort: false },
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      threeId: '',
      partId: ''
    };
  },
  components: {
    detail, addForm, importExcel
  },
  async created() {
    let res = await assemblyAndRegulationsListRecordNew({
      isDeleted: 0,
      pageNum: 1,
      currentPage: 1,
      pageSize: 99999,
      limit: 99999,
    });
    if (res.resultCode === 200) {
      this.topFilterList.find(x=>x.fieldName=='assemblyCode').itemList = res.data.records.map(y => ({ text: y.assemblyCode, value: y.assemblyCode }));
    }
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    // Excel更新导入
    showImportFun() {
      this.showImport = true;
    },
    //下载模板
    downloadTemplate() {
      this.$confirm('此操作将下载excel模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true;
        downloadModel().then(res => {
          console.log(res);
          exportExcelFile(res.data, '总成及主要备件关系维护导入模板');
          this.exportLoading = false;
        });
      });
    },
    importClose() {
      this.showImport = false;
      this.fetchParams = { ...this.fetchParams };
    },
    add() {
      this.visibleAdd = true;
    },
    addSave() {
      this.visibleAdd = false;
      this.fetchParams = { ...this.fetchParams };
    },
    editSave() {
      this.visibleDetail = false;
      this.fetchParams = { ...this.fetchParams };
    },
    async exportHandle() {
      const [err, params] = await this.$refs.topfilter.GET_FORM_DATA();

      await this.downHandleFile(exportListRecord, params, '三包法规查询');
    },

    // 导出处理函数
    handleExportFun(row) {
      row.type = this.createDictText(row.type, 1023);
    },

    detailHandle(row) {
      this.partId = row['partId'];
      this.handleType = 'show';
      this.showHandler();
    },
    async deleteHandle(row) {
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.partId = row['partId'];
          let params = Object.assign({}, {partId: this.partId});

          this.loading = true;
          let res = await deleteAssemblyPart(params);
          if (res.resultCode === 200) {
            this.$notify.success({title: '提示信息', message: '删除成功'});
            this.fetchParams = {...this.fetchParams};
          } else {
            this.loading = false;
            this.$notify.error({title: '提示信息', message: res.errMsg || '删除失败!'});
          }
          this.loading = false;
        });
    },

    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '总成编号',
          dataIndex: 'assemblyCode',
          sorter: true,
          width: 170,
        },
        {
          title: '总成名称',
          dataIndex: 'assemblyName',
          sorter: true,
          width: 170,
        },
        {
          title: '备件编号',
          dataIndex: 'partNo',
          sorter: true,
          width: 170,
        },
        {
          title: '备件名称',
          dataIndex: 'partName',
          sorter: true,
          width: 170,
        },
        {
          title: '关系描述',
          dataIndex: 'remarks',
          sorter: true,
          showOverflowTooltip: false,
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.detailHandle(props.row)}>
                  修改
                </el-button>
                <el-divider direction="vertical"/>
                <multiuse-button size="mini" type="text" onClick={() => this.deleteHandle(props.row)}>
                  删除
                </multiuse-button>
              </div>
            );
          }
        },
      ];
    },
    createTopFilterList() {
      return [
        {
          type: 'SELECT',
          label: '总成编号',
          fieldName: 'assemblyCode',
          placeholder: '请选择总成编号...',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '总成名称',
          fieldName: 'assemblyName',
          placeholder: '请输入总成名称...'
        },
        {
          type: 'INPUT',
          label: '备件编号',
          fieldName: 'partNo',
          placeholder: '请输入备件编号...'
        },
        {
          type: 'INPUT',
          label: '备件名称',
          fieldName: 'partName',
          placeholder: '请输入备件名称...'
        }
      ];
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },

    changeHandle(val) {
      // val.bDate=moment(val['bDate']).format('YYYY-MM-DD')
      // val.eDate=moment(val['eDate']).format('YYYY-MM-DD')
      this.fetchParams = Object.assign({}, val);

      console.log(this.fetchParams);
    },
    showHandler() {
      this.dialogTitle = `${this.conf[this.handleType]}`;

      this.visibleDetail = true;
    },

    closeHandler(type) {
      this.visible = false;
      this.visibleDetail = false;
      this.visibleAdd = false;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    }
  }
};
</script>

<style lang="less" scoped></style>
